package com.example.springbooteasycode.utils;

import java.io.InputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class ImageDownloader {

    public static void main(String[] args) throws Exception {
        try {
            byte[] imageData = ImageDownloader.downloadImage("https://mmbiz.qpic.cn/mmbiz_gif/fibicxlqcY285fFBxYZZGQz4p1D9RXhzF15OXaCMVshYiaBvs0uibelyNRTdDvJkRW5IgiamWqPDC5tcv3ufKicKOIKw/640?wx_fmt=gif");
        System.out.println(imageData);
        } catch (Exception e) {
            e.printStackTrace();

        }
    }
    public static byte[] downloadImage(String imageUrl) throws Exception {
        URL url = new URL(imageUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);

        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = connection.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

            return out.toByteArray();
        } else {
            throw new RuntimeException("Failed to download image with status code: " + responseCode);
        }
    }
}
